<script setup lang="ts">
import { ref, computed, watch,onMounted, nextTick } from 'vue'
import { Handle, Position, useVueFlow } from '@vue-flow/core'
import StyleSet from './StyleSet.vue';
defineOptions({
  name: 'STTNode'
})

const props = defineProps<{
  id: string;
  data: {
    name: string;
    algorithm?: string;
    model?: string;
    language?: string;
    confidenceThreshold?: number;
    enablePunctuation?: boolean;
    enableWordTimestamps?: boolean;
  };
  toObject?:()=>any
}>()

const { updateNodeData,updateNode } = useVueFlow()
const name = computed({
  get: () => props.data.name,
  set: (name) => updateNodeData(props.id, {...props.data, name: name }),
})

import useConnectionValid from './ts/connectionValid';
const { isValidConnection } = useConnectionValid();

// STT configuration options
const algorithm = ref<AlgorithmType>(props.data.algorithm as AlgorithmType || 'whisper');
const model = ref(props.data.model || 'base');
const language = ref(props.data.language || 'en');
const confidenceThreshold = ref(props.data.confidenceThreshold || 0.8);
const enablePunctuation = ref(props.data.enablePunctuation ?? true);
const enableWordTimestamps = ref(props.data.enableWordTimestamps ?? false);

import type { AlgorithmType } from './ts/STTNode_op'
import { algorithmOptions, modelOptions, languageOptions } from './ts/STTNode_op'
// Watch for changes and update node data
watch(() => [
  algorithm.value,
  model.value,
  language.value,
  confidenceThreshold.value,
  enablePunctuation.value,
  enableWordTimestamps.value
], () => {
  updateNodeData(props.id, {
    ...props.data,
    algorithm: algorithm.value,
    model: model.value,
    language: language.value,
    confidenceThreshold: confidenceThreshold.value,
    enablePunctuation: enablePunctuation.value,
    enableWordTimestamps: enableWordTimestamps.value
  })
})
const AgentContentConainer = ref<HTMLElement | null>(null);

import { useProjectsStore } from '@/stores/projectsStore';
import type { Styles } from '@vue-flow/core';
let projectStore = useProjectsStore();
onMounted(() => {
  // console.log("props:", props)
    let now_store_node = projectStore.getNode(props.id);
    let STY = <Styles>now_store_node?.style || {};
    if (now_store_node) {
      WW.value = STY?.minWidth ? parseInt(STY.minWidth.toString()) : MaxWW;
      HH.value = STY?.minHeight ? parseInt(STY.minHeight.toString()) : MaxHH;
      Color.value = STY?.backgroundColor || SttBackground;
    }
    nextTick(() => {
    if (!AgentContentConainer.value) return;
    updateSize();
    const { width, height } = AgentContentConainer.value!.getBoundingClientRect();
    //console.log('AgentContentConainer:', width, height);
    })
});

import { SttMinW, SttMinH, SttBackground } from './ts/default-node-style';
const MaxWW=SttMinW;
const MaxHH=SttMinH;
const WW = ref(MaxWW);
const HH = ref(MaxHH);
const Color= ref(SttBackground);
const updateColor=(color:string)=>{
  Color.value = color;
  updateSize()
}
const onChangeSize = () => {
  updateSize()
}

const updateSize=()=>{
  WW.value = Math.max(WW.value, MaxWW);
  HH.value = Math.max(HH.value, MaxHH);
  updateNode(props.id, {...props, style:{minWidth: `${WW.value}px`,minHeight: `${HH.value}px`,backgroundColor: Color.value}})
  //console.log('更新样式:',props.toObject?.())
}
</script>

<template>
  <div class="NodeName">
    <input :id="`${id}-input`" v-model="name" class="nodrag" />
  </div>
  <div class="NodeContent" ref="AgentContentConainer">
    <!-- Input Handles -->
    <Handle id="flow-in" type="target" :class="['AgentFlowInputHandle', 'top-0']" :position="Position.Left" title="Flow In"
      :connectable="() => isValidConnection(props.id, 'flow-in', 'target')">
      <span class="HandleLeftSpan">Flow In</span>
    </Handle>
    <Handle id="cached-audio" type="target" :class="['AgentAudio', 'top-2']" :position="Position.Left" title="Cached Audio"
      :connectable="() => isValidConnection(props.id, 'cached-audio', 'target')">
      <span class="HandleLeftSpan">Cached Audio</span>
    </Handle>

    <!-- Output Handles -->
    <Handle id="flow-next" type="source" :class="['AgentFlowOutputHandle', 'top-0']" :position="Position.Right" title="Flow Next"
      :connectable="() => isValidConnection(props.id, 'flow-next', 'source')">
      <span class="HandleRightSpan">Flow Next</span>
    </Handle>
    <Handle id="msg" type="source" :class="['AgentMsg', 'top-1']" :position="Position.Right" title="Message"
      :connectable="() => isValidConnection(props.id, 'msg', 'source')">
      <span class="HandleRightSpan">Message</span>
    </Handle>
    <Handle id="flow-next-end" type="source" :class="['AgentFlowOutputHandle', 'top-2']" :position="Position.Right" title="Sentence End"
      :connectable="() => isValidConnection(props.id, 'flow-next-end', 'source')">
      <span class="HandleRightSpan">Sentence End</span>
    </Handle>
    <Handle id="end-msg" type="source" :class="['AgentMsg', 'top-3']" :position="Position.Right" title="End Message"
      :connectable="() => isValidConnection(props.id, 'end-msg', 'source')">
      <span class="HandleRightSpan">End Message</span>
    </Handle>

    
    <div class="NodeData">
      <div class="select-row">
        <label for="algorithm">Algorithm:</label>
        <select id="algorithm" v-model="algorithm" class="select-input nodrag">
          <option v-for="option in algorithmOptions" :key="option.value" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </div>

      <!-- Model Selection -->
      <div class="select-row">
        <label for="model">Model:</label>
        <select id="model" v-model="model" class="select-input nodrag">
          <option v-for="option in modelOptions[algorithm]" :key="option.value" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </div>

      <!-- Language Selection -->
      <div class="select-row">
        <label for="language">Language:</label>
        <select id="language" v-model="language" class="select-input nodrag">
          <option v-for="option in languageOptions" :key="option.value" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </div>

      <!-- Confidence Threshold -->
      <div class="input-row">
        <label for="confidenceThreshold">Confidence Threshold:</label>
        <input
          id="confidenceThreshold"
          type="number"
          v-model="confidenceThreshold"
          min="0"
          max="1"
          step="0.1"
          class="text-input nodrag"
        />
      </div>

      <!-- Checkbox Options -->
      <div class="checkbox-row">
        <label for="enablePunctuation">Enable Punctuation</label>
        <input
          id="enablePunctuation"
          type="checkbox"
          v-model="enablePunctuation"
          class="checkbox nodrag"
        />
      </div>

      <div class="checkbox-row">
        <label for="enableWordTimestamps">Enable Word Timestamps</label>
        <input
          id="enableWordTimestamps"
          type="checkbox"
          v-model="enableWordTimestamps"
          class="checkbox nodrag"
        />
      </div>
    </div>
  </div>
 <div class="setfooter2" style="height:30px;width:200px;">
    W:<span class="input2"> <input :id="`${id}-input1`" v-model="WW" class="nodrag" @change="onChangeSize" min="200" max="1000"> </span>
    H:<span class="input2"> <input :id="`${id}-input2`" v-model="HH" class="nodrag" @change="onChangeSize" min="100" max="500"> </span>
  </div>
  <div class="setfooter" style="height:30px;width:70px;">
    <StyleSet @update_style_color="updateColor"></StyleSet>
  </div>
</template>

<style scoped>

.setfooter{
position: absolute;
right:0;
bottom:3px;
}
.setfooter2{
position: absolute;
left:3px;
bottom:0px;
}
.input2 {
  position: relative;
  display: inline-block;
  font-size: 14px;
  text-align: center;
}
.input2 input {
  max-height: 20px;
  height:30px;
  width: 50px;
  border: none;
  outline: none;
  background: transparent;
  color: #333;
  font-size: 16px;
  padding: 8px 12px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  text-align: center;
  background-color: #00000000;
}
</style> 